import { requestAndroidPermission, judgeIosPermission, gotoAppPermissionSetting } from "./permission"
const systemInfo = uni.getSystemInfoSync()
const platform = systemInfo.platform
const permissionIDMap = platform === 'ios' ? {
	location: 'location',
	push: 'push',
	camera: 'camera',
	photoLibrary: 'photoLibrary',
	record: 'record',
	contact: 'contact',
	calendar: 'calendar',
	memo: 'memo'
} : {
	location: 'android.permission.ACCESS_FINE_LOCATION',
	camera: 'android.permission.CAMERA',
	photoLibrary: 'android.permission.READ_EXTERNAL_STORAGE',
	newPhotoLibrary: 'android.permission.READ_MEDIA_IMAGES',
	record: 'android.permission.RECORD_AUDIO',
	contact: 'android.permission.READ_CONTACTS',
	calendar: 'android.permission.READ_CALENDAR',
}

const AppPermision = platform === 'ios' ? (permissionID : string) => { return new Promise((resolve, reject) => resolve(judgeIosPermission(permissionID))) } : requestAndroidPermission

const showPermissionModal = (key : string, title1 : string, title2 : string) => {
	key = `app-get-${key}-prmission-time`
	const nowDate = new Date().getTime()
	let oldDate = uni.getStorageSync(key)
	if (!oldDate || (nowDate - oldDate) > 172800) {
		// 若用户永久拒绝获取权限，最少需间隔48小时才能再次请求获取权限
		uni.showModal({
			content: title1,
			success: (res) => {
				if (res.confirm) {
					gotoAppPermissionSetting()
				} else {
					uni.setStorageSync(key, nowDate)
				}
			}
		});
	} else {
		uni.showToast({
			title: title2,
			duration: 2000,
			position: 'bottom',
		})
	}

}
const showAskPermissionModal = (key : string, content : string) => new Promise((resolve, reject) => {
	key = `app-ask-${key}-prmission-time`
	if (uni.getStorageSync(key)) {
		resolve(true)
		return
	}
	uni.showModal({
		title: "提示",
		content: `${systemInfo.appName}申请${content}`,
		success(res) {
			if (res.confirm) {
				uni.setStorageSync(key, true)
				resolve(true)
			} else {
				reject(false)
			}
		}
	})
})
// 权限在本次app运行中是否已经索取过且被拒绝或忽略权限申请，是则会被缓存到checkPermisionkeys中，在本次运行中将不会再索取权限
const checkPermisionkeys : string[] = []
// 相机权限
export const checkCamera = ():Promise<boolean> => {
	return new Promise(async (resolve, reject) => {
		// #ifdef APP
		const permissionID = permissionIDMap.camera
		try {
			await showAskPermissionModal(permissionID, "获取设备的摄像头权限，用于拍照上传功能")
		} catch (e) {
			reject(false)
			return
		}
		if (checkPermisionkeys.includes(permissionID)) {
			reject(false)
			return
		}
		const result = await AppPermision(permissionID)
		// 权限被拒绝
		if (platform === 'android' && result !== 1 || platform === 'ios' && !result) {
			checkPermisionkeys.push(permissionID)
			if (platform === 'android') {
				let strStatus = result == 0 ? "未获得授权" : "被永久拒绝"
				showPermissionModal(permissionID, `相机权限${strStatus},是否前往开启？`, `相机权限}${strStatus}`)
			}
			reject(false)
			return
		} else {
			resolve(true)
		}
		// #endif
		// #ifdef MP
		uni.authorize({
			scope: 'scope.camera',
			success() {
				resolve(true)
			},
			fail() {
				reject(false)
			}
		})
		// #endif
	})
}
const {osVersion} = uni.getSystemInfoSync();
// android13及以上，读取相册需要使用该权限,而不是原来的外部存储读取权限
const checkNewPhotoLibrary = ():Promise<boolean> => {
	return new Promise(async (resolve, reject) => {
		// #ifdef APP
		const permissionID = permissionIDMap.newPhotoLibrary
		try {
			await showAskPermissionModal(permissionID, "获取设备的相册读取权限，用于图片上传功能")
		} catch (e) {
			reject(false)
			return
		}
		if (checkPermisionkeys.includes(permissionID)) {
			reject(false)
			return
		}
		const result = await AppPermision(permissionID)
		// 权限被拒绝
		if (platform === 'android' && result !== 1 || platform === 'ios' && !result) {
			checkPermisionkeys.push(permissionID)
			if (platform === 'android') {
				let strStatus = result === 0 ? "未获得授权" : "被永久拒绝"

				showPermissionModal(permissionID, `相册读取权限${strStatus},是否前往开启？`, `相册读取权限}${strStatus}`)
			}
			reject(false)
			return
		}
		// #endif
		resolve(true)
	})
}

// 相册权限
export const checkPhotoLibrary = ():Promise<boolean> => {
	return new Promise(async (resolve, reject) => {
		if(Number(osVersion) > 12){
			checkNewPhotoLibrary().then(() => {
				resolve(true)
			}).catch(() => {
				reject(false)
			})
			return 
		}
		// #ifdef APP
		const permissionID = permissionIDMap.photoLibrary
		try {
			await showAskPermissionModal(permissionID, "获取设备的外部存储读取权限，用于图片上传功能")
		} catch (e) {
			reject(false)
			return
		}
		if (checkPermisionkeys.includes(permissionID)) {
			reject(false)
			return
		}
		const result = await AppPermision(permissionID)
		// 权限被拒绝
		if (platform === 'android' && result !== 1 || platform === 'ios' && !result) {
			checkPermisionkeys.push(permissionID)
			if (platform === 'android') {
				let strStatus = result === 0 ? "未获得授权" : "被永久拒绝"

				showPermissionModal(permissionID, `外部存储读取权限${strStatus},是否前往开启？`, `外部存储读取权限}${strStatus}`)
			}
			reject(false)
			return
		}
		// #endif
		resolve(true)
	})
}
// 外部存储权限
export const checkExternalStorage = ():Promise<boolean> => {
	return new Promise(async (resolve, reject) => {
		// #ifdef APP

		const permissionID = 'android.permission.WRITE_EXTERNAL_STORAGE'
		try {
			await showAskPermissionModal(permissionID, "获取设备的外部存储写入权限，用于保存图片、视频或文件功能")
		} catch (e) {
			reject(false)
			return
		}
		if (checkPermisionkeys.includes(permissionID)) {
			reject(false)
			return
		}
		const result = await AppPermision(permissionID)
		if (platform === 'android' && result !== 1 || platform === 'ios' && !result) {
			checkPermisionkeys.push(permissionID)
			if (platform === 'android') {
				let strStatus = result === 0 ? "未获得授权" : "被永久拒绝"
				showPermissionModal(permissionID, `外部存储写入权限${strStatus},是否前往开启？`, `外部存储写入权限}${strStatus}`)
			}
			reject(false)
			return
		}

		// #endif
		resolve(true)
	})
}
// 电话权限
export const checkMakePhoneCall = ():Promise<boolean> => {
	return new Promise(async (resolve, reject) => {
		// #ifdef APP
		// 电话权限只需判断android
		if (platform === 'android') {
			const permissionID = 'android.permission.CALL_PHONE'
			try {
				await showAskPermissionModal(permissionID, "获取设备的电话权限，用于拨打电话功能")
			} catch (e) {
				reject(false)
				return
			}
			if (checkPermisionkeys.includes(permissionID)) {
				reject(false)
				return
			}
			const result = await AppPermision(permissionID)
			if (result !== 1) {
				checkPermisionkeys.push(permissionID)
				let strStatus = result == 0 ? "未获得授权" : "被永久拒绝"
				showPermissionModal(permissionID, `拨打电话权限${strStatus},是否前往开启？`, `拨打电话权限${strStatus}`)
				reject(false)
				return
			}
		}
		// #endif
		resolve(true)
	})
}
// 定位权限
export const checkLocationPermission = ():Promise<boolean> => {
	return new Promise(async (resolve, reject) => {
		// #ifdef APP

		const permissionID = permissionIDMap.location
		try {
			await showAskPermissionModal(permissionID, "获取设备的位置权限，以获取您当前的位置信息")
		} catch (e) {
			reject(false)
			return
		}
		if (checkPermisionkeys.includes(permissionID)) {
			reject(false)
			return
		}
		const result = await AppPermision(permissionID)
		// 权限被拒绝
		if (platform === 'android' && result !== 1 || platform === 'ios' && !result) {
			checkPermisionkeys.push(permissionID)
			if (platform === 'android') {
				let strStatus = result == 0 ? "未获得授权" : "被永久拒绝"
				showPermissionModal(permissionID, `位置权限${strStatus},是否前往开启？`, `位置权限${strStatus}`)
			}
			reject(false)
			return
		} else {
			resolve(true)
		}


		// #endif
		// #ifdef MP
		uni.authorize({
			scope: 'scope.userLocation',
			success() {
				resolve(true)
			},
			fail() {
				reject(false)
			}
		})
		// #endif
	})
}

// 麦克风权限
export const checkRecorderManager = ():Promise<boolean> => {
	return new Promise(async (resolve, reject) => {
		// #ifdef APP
		// 麦克风权限只需判断android
		if (platform === 'android') {
			const permissionID = 'android.permission.RECORD_AUDIO'
			try {
				await showAskPermissionModal(permissionID, "获取设备的麦克风权限，用于使用语言消息功能等")
			} catch (e) {
				reject(false)
				return
			}
			if (checkPermisionkeys.includes(permissionID)) {
				reject(false)
				return
			}
			const result = await AppPermision(permissionID)
			if (result !== 1) {
				checkPermisionkeys.push(permissionID)
				let strStatus = result == 0 ? "未获得授权" : "被永久拒绝"
				showPermissionModal(permissionID, `麦克风权限${strStatus},是否前往开启？`, `麦克风权限${strStatus}`)
				reject(false)
				return
			}
		}
		// #endif
		resolve(true)
	})
}